// subpkg/issue/issue.js
//调用数据库
const db = wx.cloud.database()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        scrollHeight: 0,
        goodsId: '',               // 存储添加数据库记录后返回的商品_id
        goodsName: '',
        goodsDesc: '',
        goodsPrice: '',
        goodsBeforPrice: '',
        goodsWay: '',
        imgList: [],               // 存放上传图片路径
        type: '',                  // 存储商品类型
        typeIndex: -1,             // 分类标记
        num: 1,                    // 库存初始数量
        categoryList: ["书籍", "用品", "箱包", "其它"], //定义分类标签
        minusStatus: 'disable',    // 加减号按钮状态
        fontCount: 0,              // 详情框输入字数
        wayList: ["自提", "配送"],  // 商品方式集合
        textFlag: '提交',           // 用于判断是发布(提交)还是修改
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options) {
            let textFlag = '提交';
            if(options.text) {
                textFlag = options.text;
                wx.setNavigationBarTitle({
                  title: options.text + '商品',
                });
            }
            let goodsId = options.id ? options.id : '';
            this.setData({
                textFlag: textFlag,
                goodsId: goodsId
            });
        }
    },
    /**
     * 监听商品名输入
     * @param {*} e 
     */
    onCinName(e) {
        this.data.goodsName = e.detail.value;
    },
    /**
     * 详情框动态监听字数
     */
    onCinDesc(e) {
        this.setData({
            fontCount: e.detail.cursor,
            goodsDesc: e.detail.value
        });
    },
    /**
     * 分类选择
     */
    typeSelect(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            typeIndex: index,
            type: this.data.categoryList[index] //存储商品分类
        });
    },
    /**
     * 库存加减框处理事件函数
     */
    /*点击减号*/
    bindMinus: function () {
        let num = this.data.num;
        if (num > 1) {
            num--;
        }
        let minusStatus = num > 1 ? 'normal' : 'disable';
        this.setData({
            num: num,
            minusStatus: minusStatus
        });
    },
    /*点击加号*/
    bindPlus: function () {
        let num = this.data.num;
        num++;
        let minusStatus = num > 1 ? 'normal' : 'disable';
        this.setData({
            num: num,
            minusStatus: minusStatus
        })
    },
    /*输入框事件*/
    bindManual: function (e) {
        var num = e.detail.value;
        var minusStatus = num > 1 ? 'normal' : 'disable';
        this.setData({
            num: num,
            minusStatus: minusStatus
        })
    },
    /**
     * 输入售价
     * @param {*} e 
     */
    onCinPrice(e) {
        this.data.goodsPrice = parseFloat(e.detail.value);
    },
    /**
     * 输入原价
     * @param {*} e 
     */
    onCinBeforePrice(e) {
        this.data.goodsBeforPrice = parseFloat(e.detail.value);
    },
    onChangeRadio(e) {
        this.data.goodsWay = e.detail.value;
    },
    /**
     * 表单提交事件
     */
    onAddGoods(e) {
        if(this.data.goodsName === '' || this.data.goodsName.length < 1) {
            this.$showMsg('请填写商品名');
        }else if(this.data.imgList.length < 1) {
            this.$showMsg('请至少上传一张图片');
        }else if(this.data.typeIndex < 0) {
            this.$showMsg('请选择商品分类');
        }else if(this.data.goodsPrice === 0 || Object.is(this.data.goodsPrice, NaN)) {
            this.$showMsg('请输入正常商品售价');
        }else if(this.data.goodsBeforPrice === 0 || Object.is(this.data.goodsBeforPrice, NaN)) {
            this.$showMsg('请输入正常商品原价');
        }else if(this.data.goodsWay === '') {
            this.$showMsg('请选择发货方式');
        }else {
            // 信息完整，提交
            if(this.data.textFlag === '提交') {
                // 发布商品
                this.addIdlemallGoods();
            }else {
                // 编辑已发布商品
                this.updateIdlemallGoods();
            }
            
        }
    },
    /**
     * 添加闲置商品
     */
    async addIdlemallGoods() {
        // 信息完整，上传图片
        let cloudImgList = [];
        for(let i = 0; i < this.data.imgList.length; i++) {
            let res = await wx.cloud.uploadFile({
                cloudPath: 'goods/' + this.getRandomStr() + '.' + this.data.imgList[i].split('.')[1],
                filePath: this.data.imgList[i]
            });
            if(res.errMsg === 'cloud.uploadFile:ok') {
                cloudImgList.push(res.fileID);
            }
        }
        // 包装数据
        let goodsForm = {};
        goodsForm.goodsData = {};
        goodsForm.goodsData.goodsName = this.data.goodsName;
        goodsForm.goodsData.goodsDetail = this.data.goodsDesc;
        goodsForm.goodsData.goodsBefore = this.data.goodsBeforPrice;
        goodsForm.goodsData.goodsPrice = this.data.goodsPrice;
        goodsForm.goodsData.goodsWay = this.data.goodsWay;
        goodsForm.goodsData.goodsNum = this.data.num;
        goodsForm.goodsImg = cloudImgList;
        goodsForm.goodsStatus = this.data.num === 0 ? '无库存' : (this.data.goodsStatus === '已下架' ? '已下架' : '出售中');
        goodsForm.goodsType = this.data.type;
        console.log('add goodsForm ==>', goodsForm);
        db.collection('idlemallSend').add({
            data: goodsForm
        }).then(res => {
            console.log('add goods success ==>', res);
            wx.redirectTo({
              url: '/subpkg/issueSuccess/issueSuccess?flag=2&id=' + res._id,
            });
        }, err => {
            console.log('add goods error ==>', err);
        });
    },
    /**
     * 修改数据
     */
    async updateIdlemallGoods() {
        // 信息完整，上传图片
        let cloudImgList = [];
        // 用于匹配 cloud 协议的文件链接
        let rStr = /cloud.*/;
        for(let i = 0; i < this.data.imgList.length; i++) {
            // 判断图片是否更改
            if(rStr.test(this.data.imgList[i])) {
                cloudImgList.push(this.data.imgList[i]);
            }else {
                let res = await wx.cloud.uploadFile({
                    cloudPath: 'goods/' + this.getRandomStr() + '.' + this.data.imgList[i].split('.')[1],
                    filePath: this.data.imgList[i]
                });
                if(res.errMsg === 'cloud.uploadFile:ok') {
                    cloudImgList.push(res.fileID);
                }
            }
        }
        // 包装数据
        let goodsForm = {};
        goodsForm.goodsData = {};
        goodsForm.goodsData.goodsName = this.data.goodsName;
        goodsForm.goodsData.goodsDetail = this.data.goodsDesc;
        goodsForm.goodsData.goodsBefore = this.data.goodsBeforPrice;
        goodsForm.goodsData.goodsPrice = this.data.goodsPrice;
        goodsForm.goodsData.goodsWay = this.data.goodsWay;
        goodsForm.goodsData.goodsNum = this.data.num;
        goodsForm.goodsImg = cloudImgList;
        goodsForm.goodsStatus = '出售中';
        goodsForm.goodsType = this.data.type;
        console.log('update goodsForm ==>', goodsForm);
        db.collection('idlemallSend').doc(this.data.goodsId).update({
            data: goodsForm
        }).then(res => {
            console.log('update goods success ==>', res);
            wx.redirectTo({
                url: '/subpkg/issueSuccess/issueSuccess?flag=1&id=' + this.data.goodsId,
              });
        }, err => {
            console.log('update goods error ==>', err);
        });
    },
    /**
     * 上传图片
     */
    chooseImg() {
        // 最大支持5张图片
        if(this.data.imgList.length < 5) {
            wx.chooseMedia({
                count: 5,
                mediaType: ['image'],
                sourceType: ['album']
            }).then(res => {
                // console.log('chooseMedia success ==>', res);
                for(let i = 0; i < res.tempFiles.length; i++) {
                    this.data.imgList.push(res.tempFiles[i].tempFilePath);
                }
                this.setData({
                    imgList: this.data.imgList
                });
            }, err => {
                console.log('chooseMedia error ==>', err);
            });
        }else {
            this.$showMsg('最多上传5张图片');
        }
    },
    /**
     * 删除图片
     * @param {*} e 
     */
    onToDelete(e) {
        let index = e.currentTarget.dataset.index;
        this.data.imgList.splice(index, 1);
        this.setData({
            imgList: this.data.imgList
        });
    },
    /**
     * 根据 id 获取商品数据
     */
    getGoodsById(id) {
        db.collection('idlemallSend').doc(id).get()
          .then(res => {
              // console.log('get goods by id success ==>', res);
              this.setData({
                  goodsName: res.data.goodsData.goodsName,
                  goodsDesc: res.data.goodsData.goodsDetail,
                  goodsPrice: res.data.goodsData.goodsPrice,
                  goodsBeforPrice: res.data.goodsData.goodsBefore,
                  num: res.data.goodsData.goodsNum,
                  goodsWay: res.data.goodsData.goodsWay,
                  imgList: res.data.goodsImg,
                  goodsStatus: res.data.goodsStatus,
                  type: res.data.goodsType,
                  typeIndex: this.data.categoryList.indexOf(res.data.goodsType),
                  fontCount: res.data.goodsData.goodsDetail.length,
                  minusStatus: res.data.goodsData.goodsNum > 1 ? 'normal' : 'disable'
              });
          }, err => {
              console.log('get goods by id error ==>', err);
          });
    },
    /**
     * 获取随机字符串-16位
     */
    getRandomStr() {
        let str = '';
        str += new Date().getTime() + ('000' + Math.floor(Math.random() * 1000)).slice(-3);
        return str;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getScrollHeight();
        if(this.data.goodsId) {
            this.getGoodsById(this.data.goodsId);
        }
    },
    /**
     * 获取滚动视图高
     */
    getScrollHeight() {
        this.setData({
            scrollHeight: wx.getSystemInfoSync().windowHeight - 100
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    /**
     * 显示提示信息
     * @param {*} msg 
     * @param {*} type 
     */
    $showMsg(msg, type = 'none') {
        wx.showToast({
          title: msg,
          icon: type
        });
    }
})